<?php

namespace App\Http\Controllers\Mobile\Company;
use App\Facades\Site;
use App\Http\Requests\Company\Job\AddJobRequest;
use App\Http\Requests\Company\Job\UpdateJobRequest;
use App\Models\Common\CollArea;
//use App\Models\Company\CompanyBasic;
//use App\Models\Company\CompanyContact;
//use App\Models\Company\CompanyDepartment;
//use App\Models\Company\CompanyJob;
use App\Models\Common\CollOption;
use App\Models\Common\CollPosition;
use App\Models\Company\CompanyBasic;
use App\Models\Company\CompanyContact;
use App\Models\Company\CompanyDepartment;
use App\Models\Company\CompanyJob;
use App\Models\Company\CompanyRefreshLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Facades\Style;

class JobController extends CommonController{

    /**
     * 职位发布提交
     * @param Request $request
     * @return mixed
     */
    public function publish(Request $request){
        $user=auth()->guard('company')->user();
        $companyBasic=CompanyBasic::where('uid',$user->uid)->orderBy('updatetime', 'desc')->first();
        //企业不存在时
        if(empty($companyBasic)){
            return redirect("mobile/company/register_basic");
        }
        $companyBasic->cn_region=CollArea::getAreaName($companyBasic->region);
        //获取部门
        $companyDepartment=CompanyDepartment::where('uid',$user->uid)->select(['id','name'])->get();
        $department = array();
        if(count($companyDepartment) > 0 ) {
            foreach ($companyDepartment as $v) {
                $department[] = array(
                    'value'=>$v->id,'text'=>$v->name
                );
            }
        }
        $department =  json_encode($department);
        return Style::view('mobile.company.jobpublish',compact('companyDepartment','department','companyBasic'));
    }

    /**
     * 数据库添加职位
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(AddJobRequest $request){
        $user=auth()->guard('company')->user();
        if($user->postNumber()>0) {
            $input = $request->only('job_title', 'part_status', 'job_category1', 'job_category2', 'job_category3', 'job_category4', 'job_category5', 'industry', 'location1',
                'location2', 'location3', 'location4', 'location5', 'department', 'recruiting_num', 'salary_above', 'salary_below', 'description', 'education', 'work_year'
                , 'age_above', 'age_below', 'gender', 'language', 'welfare', 'contact_info');

            $input['addtime'] = date('Y-m-d H:i:s', time());
            $input['updatetime'] = date('Y-m-d H:i:s', time());
            $input['uid'] = $user->uid;
            $CompanyBasic = CompanyBasic::where('uid', $user->uid)->orderBy('updatetime', 'desc')->first();
            $input['com_id'] = $CompanyBasic->id;
            //审核状态设置
            switch (Site::get('job_review')) {
                case  1:
                    $input['job_status'] = 1;
                    break;
                case  2:
                    $input['job_status'] = ($user->viptime >= date('Y-m-d H:i:s')) ? 1 : 0;
                    break;
                case  3:
                    $input['job_status'] = 0;
                    break;
                default:
                    $input['job_status'] = 0;
            }
            $companyJob = CompanyJob::create($input);
            if ($request->contact_info == 2) {
                $input = $request->only('contacts', 'mobile', 'phone', 'fax', 'email');
                $input['job_id'] = $companyJob->id;
                $input['uid'] = $user->uid;
                $input['addtime'] = date('Y-m-d H:i:s', time());
                $input['updatetime'] = date('Y-m-d H:i:s', time());
                CompanyContact::create($input);
            }
            return redirect('mobile/company/jobadmin');
        }else{
            return back()->withInput()->with('info', "您的职位数已用完请先购买!");
        }
    }

    /**
     * 职位管理
     * @param Request $request
     * @return mixed
     */
    public function admin(Request $request){
        $user=auth()->guard('company')->user();
        //获取面试通知记录
        $joblist = DB::table('company_job as t1')
            ->join('company_basic as t2', 't1.com_id', '=', 't2.id')
            ->select(
                't1.id','t1.updatetime','t1.com_id','t1.recruiting_num','t1.location1','t1.education','t1.work_year',
                't2.company_name','t1.job_title','t1.contact_info','t1.salary_above','t1.salary_below','t1.job_status','t1.urgent'
            )
            ->where('t1.uid',$user->uid)
            ->where('t1.job_status','!=',4)
            ->where(function ($query) use ($request) {
                if(strlen($request->keyWord)>0){
                    $query->where('t1.job_title', 'like', '%'.$request->keyWord.'%');
                }
            })
            ->where(function ($query) use ($request) {
                if(strlen($request->job_status)>0){
                    $query->where('t1.job_status', $request->job_status);
                }
            })
            ->orderBy('updatetime','desc')
            ->orderBy('id','desc')
            ->paginate(10);

            foreach($joblist as $v){
                if($v->urgent>date('Y-m-d H:i:s',strtotime('-5 day'))){
                    $v->iurgent=1;
                }else{
                    $v->iurgent=0;
                }
                $v->job_title = str_limit($v->job_title,24);
                $v->location1  = ($v->location1) ?  CollArea::getAreaName($v->location1) : '';
                $v->education = !empty($v->education) ? CollOption::getOptionName($v->education,'education') : '';
                $v->work_year = !empty($v->work_year) ? CollOption::getOptionName($v->work_year,'work_year') : '';
            }
        $job_status=$request->job_status;
        //设置状态
        //    $job_status =  ($this->job_status!='') ? $this->job_status : '';
        return Style::view('mobile.company.jobadmin',compact('joblist','job_status'));
    }

    /**
     * 设置状态
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function status(Request $request){
        $user=auth()->guard('company')->user();
        $allow=array(1,2,4); //允许的状态码
        if(in_array($request->status,$allow)){
            if(!empty($request->id)) {
                $companyJob = CompanyJob::select('id', 'job_status')->where('uid', $user->uid)->where('id', $request->id)->first();
                if (($companyJob->job_status != 0 and $companyJob->job_status != 4) or $request->status == 4) {
                    $companyJob->job_status = $request->status;
                    $companyJob->xs_status = 0;
                    $companyJob->save();
                }
                switch($request->status){
                    case 1 : $message = '激活职位成功！';break;
                    case 2 : $message = '屏蔽职位成功！';break;
                    case 4 : $message = '删除职位成功！';break;
                    default: $message = '未知错误！';
                }
                return response()->json(['status' => 200,'message'=>$message]);
            }
        }else{
            return response()->json(['status' => 404,'message'=>"错误代码"]);
        }
    }

    /**
     * 刷新职位
     * @param Request $request
     * @return $this
     */
    public function refresh(Request $request){
        $user=auth()->guard('company')->user();

        if(CompanyRefreshLog::isRefresh()){
            $companyJob=CompanyJob::select('id','job_status')->where('job_status',1)->where('uid',$user->uid)->get();
            foreach($companyJob as $k=>$v){
                $input['updatetime']=date('Y-m-d H:i:s');
                $input['xs_status']=0;
                CompanyJob::where('uid',$user->uid)->where('id',$v->id)->update($input);
            }
            //插入刷新记录
            $CompanyRefreshLog=new CompanyRefreshLog();
            $CompanyRefreshLog->uid=$user->uid;
            $CompanyRefreshLog->refresh_time=date('Y-m-d H:i:s');
            $CompanyRefreshLog->save();
            return redirect('mobile/company/welcome')->with('ok',"刷新成功");
        }else{
            return redirect('mobile/company/welcome')->with('ok',"请明天再来刷新，vip每天最大刷新次数".CompanyRefreshLog::getMax()."次！");
        }
    }

    /**
     * 职位加急
     * @param Request $request
     * @return $this|\Illuminate\Http\RedirectResponse
     */
    public function urgent(Request $request){
        $user=auth()->guard('company')->user();
        //获取积分剩余个数
        if($user->viptime>date('Y-m-d H:i:s',time())){//会员优先使用会员积分
            $integralv=$user->vip_integral;
            $feld="vip_integral";
            if($integralv<10){
                if($user->integral>$integralv){
                    $integralv=$user->integral;
                    $feld="integral";
                }
            }
        }else{
            $integralv=$user->integral;
            $feld="integral";
        }

        if( $integralv < 10){
            if($request->ajax()){
                return response()->json(['status' => 601,'message'=>"加急失败,您的积分只有".$integralv."个!"]);
            }else{
                return back()->withInput()->with('info',"加急失败,您的积分只有".$integralv."个!");
            }
        }else{
            if(!empty($request->id)){
                $input['urgent']=date('Y-m-d H:i:s',time());
                $input['xs_status']=0;
                CompanyJob::where('uid',$user->uid)->where('id',$request->id)->update($input);
                $user->{$feld}=$integralv-10;
                $user->save();
            }
            if($request->ajax()){
                return response()->json(['status' => 200,'message'=>"加急成功,您还剩余积分".$user->{$feld}."个!"]);
            }else{
                return back()->withInput()->with('info',"加急成功,您还剩余积分".$user->{$feld}."个!");
            }
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id,Request $request){
        $user=auth()->guard('company')->user();
        $companyBasic=CompanyBasic::where('uid',$user->uid)->orderBy('updatetime', 'desc')->first();
        $companyJob=CompanyJob::where('uid',$user->uid)->where('id',$id)->first();
        $type=$request->type;
        $companyContact=CompanyContact::where('uid',$user->uid)->where('job_id',$companyJob->id)->first();

        //获取部门
        $companyDepartment=CompanyDepartment::where('uid',$user->uid)->select(['id','name'])->orderBy('updated_at', 'desc')->get();
        $department = array();
        if(count($companyDepartment) > 0 ) {
            foreach ($companyDepartment as $v) {
                $department[] = array(
                    'value'=>$v->id,'text'=>$v->name
                );
            }
        }
        $department =  json_encode($department);
        return Style::view('mobile.company.jobEdit',compact('companyDepartment','department','companyJob','companyBasic','companyContact','type'));
       }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateJobRequest $request,$id){
        $user = auth()->guard('company')->user();
        $companyJob=CompanyJob::select('id')->where('uid',$user->uid)->where('id',$id)->first();
        if($companyJob->id){
            $input = $request->only('job_title','part_status', 'job_category1', 'job_category2', 'job_category3', 'job_category4', 'job_category5', 'industry','location1',
                'location2','location3','location4','location5','department','recruiting_num','salary_above','salary_below','description','education','work_year'
                ,'age_above','age_below','gender','language','welfare','contact_info');
            $input['updatetime'] = date('Y-m-d H:i:s',time());
            //审核状态设置
            switch(Site::get('job_review')){
                case  1:
                    $input['job_status'] = 1;
                    break;
                case  2:
                    $input['job_status'] = ($user->viptime >= date('Y-m-d H:i:s')) ? 1 : 0;
                    break;
                case  3:
                    $input['job_status'] = 0;
                    break;
                default:
                    $input['job_status'] = 0;
            }
            $input['xs_status']=0;
            CompanyJob::where('id',$id)->where('uid',$user->uid)->update($input);

            if($request->contact_info==2){
                $companyContact=CompanyContact::where('uid',$user->uid)->where('job_id',$id)->first();
                $input = $request->only('contacts', 'mobile', 'phone', 'fax', 'email');
                if(!empty($companyContact->id)){
                    $input['updatetime'] = date('Y-m-d H:i:s',time());
                    CompanyContact::where('job_id',$id)->where('uid',$user->uid)->update($input);
                }else{
                    $input['job_id'] =$companyJob->id;
                    $input['uid'] =$user->uid;
                    $input['addtime'] = date('Y-m-d H:i:s',time());
                    $input['updatetime'] = date('Y-m-d H:i:s',time());
                    CompanyContact::create($input);
                }
            }
        }
        return redirect('mobile/company/jobadmin');
    }
}